package com.tbmob.tb_h5;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.ads.admob.bean.RewardPosition;
import com.alibaba.fastjson.JSON;
import com.tb.mob.TbAudioManager;
import com.tb.mob.TbManager;
import com.tb.mob.bean.Position;
import com.tb.mob.config.TbInteractionConfig;
import com.tb.mob.config.TbRewardVideoConfig;
import com.tb.mob.config.TbSplashConfig;
import com.tb.mob.utils.RequestPermission;
import com.tbmob.tb_h5.utils.AppUtils;
import com.tbmob.tb_h5.utils.PhoneUtils;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.xlx.speech.voicereadsdk.bean.AdReward;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    public ProgressBar progressBar;
    public boolean isBackPressedSupport = true;

    private WebView webView;
    private static Handler handlerMain = new Handler(Looper.getMainLooper());
    private ViewGroup a_container;
    private ViewGroup a_container_feed;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐藏标题栏
        //getSupportActionBar().hide();// 隐藏ActionBar
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 隐藏状态栏
        //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            getWindow().setAttributes(lp);
        }

        setContentView(R.layout.activity_main);
        a_container = findViewById(R.id.a_container);
        a_container_feed = findViewById(R.id.a_container_feed);
        RequestPermission.RequestPermissionIfNecessary(this);
        initWebView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        webView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        webView.onPause();
    }

    //回退键监听
    @Override
    public void onBackPressed() {
        if (webView.canGoBack() && isBackPressedSupport) {
            webView.goBack(); // goBack()表示返回WebView的上一页面
        } else {
            super.onBackPressed();
        }
    }

    private void initWebView() {
        progressBar = findViewById(R.id.a_progressBar);
        webView = findViewById(R.id.a_webView);
        WebSettings settings = webView.getSettings();
        //boolean isQbSDK = (request.getHeader("User-Agent").indexOf("qbmobSDK") >=0);
        String ua = settings.getUserAgentString();
        settings.setUserAgentString(ua + "; qbmobSDK");
        settings.setJavaScriptEnabled(true);//设置是否支持JavaScript
        //设置媒体回放需要用户手势(默认true)
        settings.setMediaPlaybackRequiresUserGesture(false);
        //设置自适应屏幕，两者合用
        settings.setUseWideViewPort(true);//将图片调整到适合webview的大小
        settings.setLoadWithOverviewMode(true);//缩放至屏幕的大小
        //缩放操作
        settings.setSupportZoom(true);//支持缩放，默认为true。是下面那个的前提。
        settings.setBuiltInZoomControls(true);//设置是否支持缩放（出现缩放工具）
        settings.setDisplayZoomControls(false);//隐藏原生的缩放控件
        //其他细节操作
        settings.setAllowFileAccess(true);//是否允许访问文件，默认允许访问
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//支持通过js打开新的窗口
        settings.setLoadsImagesAutomatically(true); //支持自动加载图片
        settings.setDefaultTextEncodingName("utf-8");//设置编码格式
        //LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
        //LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
        //LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
        //LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        //结合使用（离线加载）
        settings.setDomStorageEnabled(true);// 开启 DOM storage API 功能
        settings.setDatabaseEnabled(true);//开启 database storage API 功能
        settings.setAppCacheEnabled(true);//开启 Application Caches 功能
        settings.setSaveFormData(false);//设置WebView是否保存表单数据，默认true，保存数据
        //settings.setSupportMultipleWindows(true);//设置WebView是否支持多屏窗口，默认false，不支持。
        //settings.setUserAgentString("User-Agent:Android");//设置用户代理，一般不用
        settings.setAppCachePath(getFilesDir().getAbsolutePath() + "00_TB_MOB_SDK");//自己设置一个缓存路径
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //从Android5.0以后，当一个安全的站点（https）去加载一个非安全的站点（http）时，需要配置Webview加载内容的混合模式，一共有如下三种模式：
            settings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.addJavascriptInterface(new JsInteration(), "android");
        webView.setWebViewClient(new MyWebViewClient(this));
        webView.setWebChromeClient(new MyWebChromeClient(this));
        webView.loadUrl(ConfigInfo.h5Url);
    }

    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                if (null != uploadFile) {
                    Uri result = data == null ? null : data.getData();
                    uploadFile.onReceiveValue(result);
                    uploadFile = null;
                }
                if (null != uploadFiles) {
                    Uri result = data == null ? null : data.getData();
                    uploadFiles.onReceiveValue(new Uri[]{result});
                    uploadFiles = null;
                }
            } else if (resultCode == RESULT_CANCELED) {
                if (null != uploadFile) {
                    uploadFile.onReceiveValue(null);
                    uploadFile = null;
                }
            }
        } else if (requestCode == 200) {
            if (resultCode == 200) {
                String callBack = data.getExtras().getString("callBack");
                callBack2H5(webView, callBack, "");
            }
        }
    }

    public class JsInteration {

        @JavascriptInterface
        public void loadSplash(String codeId, String callBack) {
            handlerMain.post(new Runnable() {
                @Override
                public void run() {
                    a_container.setVisibility(View.VISIBLE);
                    TbSplashConfig config = new TbSplashConfig.Builder()
                            .codeId(codeId)
                            .container(a_container)
                            .build();
                    TbManager.loadSplash(config, MainActivity.this, new TbManager.SplashLoadListener() {
                        @Override
                        public void onFail(String msg) {
                            //加载失败
                            a_container.removeAllViews();
                            a_container.setVisibility(View.GONE);
                            Map<String, Object> map = new HashMap<>();
                            map.put("code", 0);
                            map.put("msg", "加载失败，请稍后再试=" + msg);
                            String json = JSON.toJSONString(map);
                            callBack2H5(webView, callBack, json);
                        }

                        @Override
                        public void onTick(long l) {

                        }

                        @Override
                        public void onExposure(Position position) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("code", 1);
                            map.put("msg", "加载成功并展现");
                            String json = JSON.toJSONString(map);
                            callBack2H5(webView, callBack, json);
                        }

                        @Override
                        public void onClicked() {

                        }

                        @Override
                        public void onDismiss() {
                            //被关闭
                            a_container.removeAllViews();
                            a_container.setVisibility(View.GONE);
                        }
                    });
                }
            });
        }

        @JavascriptInterface
        public void loadInteraction(String codeId, String callBack) {
            TbInteractionConfig config = new TbInteractionConfig.Builder()
                    .codeId(codeId)
                    .viewWidth(600)
                    .build();
            TbManager.loadInteraction(config, MainActivity.this, new TbManager.InteractionLoadListener() {
                @Override
                public void onFail(String msg) {
                    //加载失败
                    Map<String, Object> map = new HashMap<>();
                    map.put("code", 0);
                    map.put("msg", "加载失败，请稍后再试=" + msg);
                    String json = JSON.toJSONString(map);
                    callBack2H5(webView, callBack, json);
                }

                @Override
                public void onExposure(Position position) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("code", 1);
                    map.put("msg", "加载成功并展现");
                    String json = JSON.toJSONString(map);
                    callBack2H5(webView, callBack, json);
                }

                @Override
                public void getSDKID(Integer integer, String s) {

                }

                @Override
                public void onClicked() {

                }

                @Override
                public void onDismiss() {
                    //被关闭
                }

                @Override
                public void onVideoReady() {
                    //视频准备就绪开始播放（非视频不回调）
                }

                @Override
                public void onVideoComplete() {
                    //视频播放完成（非视频不回调）
                }
            });
        }

        @JavascriptInterface
        public void loadPlayRewardVideo(String codeId, String userId, String callExtraData, String callBack) {
            TbRewardVideoConfig config = new TbRewardVideoConfig.Builder()
                    .codeId(codeId)
                    .userId(userId)
                    .callExtraData(callExtraData)
                    .orientation(TbManager.Orientation.VIDEO_VERTICAL)
                    .build();
            TbManager.loadRewardVideo(config, MainActivity.this, new TbManager.RewardVideoLoadListener() {
                @Override
                public void onFail(String msg) {
                    //加载失败
                    Map<String, Object> map = new HashMap<>();
                    map.put("code", 0);
                    map.put("msg", "加载失败，请稍后再试=" + msg);
                    String json = JSON.toJSONString(map);
                    callBack2H5(webView, callBack, json);
                }

                @Override
                public void onExposure(String s, Position position) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("code", 1);
                    map.put("msg", "加载成功并展现");
                    String json = JSON.toJSONString(map);
                    callBack2H5(webView, callBack, json);
                }

                @Override
                public void getSDKID(Integer integer, String s) {

                }

                @Override
                public void onClick() {

                }

                @Override
                public void onClose() {
                    //视频被关闭
                }

                @Override
                public void onRewardVideoCached(RewardPosition position) {
                    //在线播放没有此回调
                }

                @Override
                public void onSkippedVideo() {

                }

                @Override
                public void onRewardVerify() {
                    //激励视频触发激励（观看视频大于一定时长或者视频播放完毕）
                    Map<String, Object> map = new HashMap<>();
                    map.put("code", 2);
                    map.put("msg", "奖励达成");
                    String json = JSON.toJSONString(map);
                    callBack2H5(webView, callBack, json);
                }
            });
        }

        @JavascriptInterface
        public void loadFeed(String codeId, String callBack) {
            handlerMain.post(new Runnable() {
                @Override
                public void run() {
                    com.tb.mob.config.TbFeedConfig config = new com.tb.mob.config.TbFeedConfig.Builder()
                            .codeId(codeId)//广告位管理列表里获取对应类型的id
                            //.viewWidth(width)//期望模板view的width，默认值350（单位dp）
                            //.viewHigh(height)//期望模板view的height，默认值0（自适应，单位dp）
                            .build();
                    com.tb.mob.TbManager.loadFeed(config, MainActivity.this, new com.tb.mob.TbManager.FeedLoadListener() {
                        @Override
                        public void onFail(String msg) {
                            //加载失败
                            Map<String, Object> map = new HashMap<>();
                            map.put("code", 0);
                            map.put("msg", "加载失败，请稍后再试=" + msg);
                            String json = JSON.toJSONString(map);
                            callBack2H5(webView, callBack, json);
                        }

                        @Override
                        public void onLoad(com.ads.admob.bean.FeedPosition position) {
                            a_container_feed.setVisibility(View.VISIBLE);
                            position.showFeed(MainActivity.this, a_container_feed);
                        }

                        @Override
                        public void onClicked() {

                        }

                        @Override
                        public void onDismiss() {
                            //关闭
                        }

                        @Override
                        public void onExposure(com.tb.mob.bean.Position position) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("code", 1);
                            map.put("msg", "加载成功并展现");
                            String json = JSON.toJSONString(map);
                            callBack2H5(webView, callBack, json);
                        }

                        @Override
                        public void onVideoReady() {
                            //视频准备就绪开始播放（非视频不回调）
                        }

                        @Override
                        public void onVideoComplete() {
                            //视频播放完成（非视频不回调）
                        }
                    });
                }
            });
        }

        @JavascriptInterface
        public void loadBanner(String codeId, String callBack) {
            handlerMain.post(new Runnable() {
                @Override
                public void run() {
                    a_container_feed.setVisibility(View.VISIBLE);
                    com.tb.mob.config.TbBannerConfig config = new com.tb.mob.config.TbBannerConfig.Builder()
                            .codeId(codeId)//广告位管理列表里获取对应类型的id
                            //.viewWidth(350)//期望模板view的width（height自适应），默认值350（单位dp）
                            //.viewHight((int) (350 / 6.4f))
                            .container(a_container_feed)//承载视图的容器
                            .build();
                    com.tb.mob.TbManager.loadBanner(config, MainActivity.this, new com.tb.mob.TbManager.BannerLoadListener() {
                        @Override
                        public void onFail(String msg) {
                            //加载失败
                            Map<String, Object> map = new HashMap<>();
                            map.put("code", 0);
                            map.put("msg", "加载失败，请稍后再试=" + msg);
                            String json = JSON.toJSONString(map);
                            callBack2H5(webView, callBack, json);
                        }

                        @Override
                        public void onClicked() {

                        }

                        @Override
                        public void onDismiss() {
                            //关闭
                        }

                        @Override
                        public void onExposure(com.tb.mob.bean.Position position) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("code", 1);
                            map.put("msg", "加载成功并展现");
                            String json = JSON.toJSONString(map);
                            callBack2H5(webView, callBack, json);
                        }
                    });
                }
            });
        }

        @JavascriptInterface
        public void closeFeedAndBanner() {
            a_container_feed.removeAllViews();
            a_container_feed.setVisibility(View.GONE);
        }

        @JavascriptInterface
        public void loadVideoAd(String codeId) {
            handlerMain.post(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(MainActivity.this, VideoFragmentActivity.class);
                    intent.putExtra("codeId", codeId);
                    startActivity(intent);
                }
            });
        }

        @JavascriptInterface
        public void loadNewsFeed(String codeId) {
            handlerMain.post(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(MainActivity.this, NewsFeedFragmentActivity.class);
                    intent.putExtra("codeId", codeId);
                    startActivity(intent);
                }
            });
        }

        @JavascriptInterface
        public void loadPlayletAd(String codeId) {
            handlerMain.post(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(MainActivity.this, PlayletFragmentActivity.class);
                    intent.putExtra("codeId", codeId);
                    startActivity(intent);
                }
            });
        }

        @JavascriptInterface
        public void loadVoiceAd(String codeId, String userId, String callBack) {
            TbAudioManager.loadVoiceAd(MainActivity.this, codeId, userId, new TbAudioManager.VoiceAdLoadListener() {
                @Override
                public void onAdLoadSuccess(float v, int i, int i1) {
                    TbAudioManager.showVoiceAd(MainActivity.this, userId, new TbAudioManager.VoiceAdListener() {
                        @Override
                        public void onAdShow() {

                        }

                        @Override
                        public void onAdError(int i) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("code", 0);
                            map.put("msg", "加载失败，请稍后再试=onAdError");
                            String json = JSON.toJSONString(map);
                            callBack2H5(webView, callBack, json);
                        }

                        @Override
                        public void onAdClose() {

                        }

                        /**
                         * 奖励验证回调，开发者在需要在此回调中做奖励的发放
                         * 如果对接多阶奖励功能，那么此回调会执行多次
                         * @param tagId 奖励唯一标识
                         * @param iCPM 千次展现实时收益，单次展现收益需要除1000
                         * @param stepNum 表示第几阶奖励
                         */
                        @Override
                        public void onRewardVerify(String tagId, float iCPM, int stepNum) {
                            Map<String, Object> map = new HashMap<>();
                            map.put("code", 1);
                            map.put("msg", "奖励达成");
                            map.put("tagId", tagId);
                            map.put("iCPM", iCPM);
                            map.put("stepNum", stepNum);
                            String json = JSON.toJSONString(map);
                            callBack2H5(webView, callBack, json);
                        }

                        /**
                         * 获取奖励信息,如果对接多阶奖励功能必须实现该方法
                         * @param iCPM 千次互动实时收益，单次互动收益需要除1000
                         * @param stepNum 表示第几阶奖励
                         */
                        @Override
                        public AdReward getRewardInfo(float iCPM, AdReward adReward, int stepNum) {
                            if (stepNum == 1) {
                                //设置奖励名称（媒体给用户发放的奖励名称）
                                adReward.setRewardName("金币");
                                //设置给用户发放的奖励值  需要开发者根据APP内虚拟币兑换比例来进行换算。比如:我方返回iCPM为100，表示此次千次互动的收益为100元，单次互动收益为0.1元。如媒体的虚拟币与人民币的兑换比例为1:10000，此次媒体的收益为1000，如果媒体给用户的分成比例为0.6，则此次应该返回600，SDK界面给用户展示为600金币
                                //adReward.setRewardCount(iCPM/1000*虚拟币的兑换比例*给用户的分成比例);
                                adReward.setRewardCount(iCPM / 1000 * 1 * 1);
                            }
                            if (stepNum == 2) {
                                //设置奖励名称（媒体给用户发放的奖励名称）
                                adReward.setRewardName("金币");
                                //设置给用户发放的奖励值  需要开发者根据APP内虚拟币兑换比例来进行换算。比如:我方返回iCPM为100，表示此次千次互动的收益为100元，单次互动收益为0.1元。如媒体的虚拟币与人民币的兑换比例为1:10000，此次媒体的收益为1000，如果媒体给用户的分成比例为0.6，则此次应该返回600，SDK界面给用户展示为600金币
                                //adReward.setRewardCount(iCPM/1000*虚拟币的兑换比例*给用户的分成比例);
                                adReward.setRewardCount(iCPM / 1000 * 1 * 1);
                            }
                            return adReward;
                        }
                    });
                }

                @Override
                public void onAdLoadError(int i, String msg) {
                    Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                    Map<String, Object> map = new HashMap<>();
                    map.put("code", 0);
                    map.put("msg", "加载失败，请稍后再试=" + msg);
                    String json = JSON.toJSONString(map);
                    callBack2H5(webView, callBack, json);
                }
            });
        }

        @JavascriptInterface
        public String getOaid() {
            Map<String, String> map = new HashMap<>();
            if (Build.VERSION.SDK_INT < 29) {
                map.put("sysver", "9");
                map.put("device", PhoneUtils.getPhoneImei(MainActivity.this));
                map.put("oaid", "");
            } else {
                map.put("sysver", "10");
                map.put("device", "");
                map.put("oaid", App.oaid);
            }
            return JSON.toJSONString(map);
        }

        @JavascriptInterface
        public String getVersion() {
            Map<String, String> map = new HashMap<>();
            String versionCode = AppUtils.getVersionCode(MainActivity.this) + "";
            String versionName = AppUtils.getVersionName(MainActivity.this);
            versionName = versionName == null ? "" : versionName;
            map.put("versionCode", versionCode);
            map.put("versionName", versionName);
            return JSON.toJSONString(map);
        }
    }

    private void callBack2H5(WebView webView, String callBack, String json) {
        handlerMain.post(new Runnable() {
            @Override
            public void run() {
                int version = Build.VERSION.SDK_INT;
                if (version < 18) {
                    if (TextUtils.isEmpty(json)) {
                        webView.loadUrl("javascript:" + callBack + "()");
                    } else {
                        webView.loadUrl("javascript:" + callBack + "(" + json + ")");
                    }
                } else {
                    if (TextUtils.isEmpty(json)) {
                        webView.evaluateJavascript("javascript:" + callBack + "()", new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {
                            }
                        });
                    } else {
                        webView.evaluateJavascript("javascript:" + callBack + "(" + json + ")", new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {
                            }
                        });
                    }
                }
            }
        });
    }
}